<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';

import { IconifyIcon } from '@vben/icons';

import {
  Button,
  Card,
  Col,
  DatePicker,
  Descriptions,
  DescriptionsItem,
  Form,
  FormItem,
  Input,
  message,
  Modal,
  Progress,
  Row,
  Select,
  SelectOption,
  Space,
  Table,
  Tag,
  Textarea,
} from 'ant-design-vue';

import StatisticsCard from '#/components/hotel/StatisticsCard.vue';

// 状态管理
const loading = ref(false);
const showAddModal = ref(false);
const showDetailModal = ref(false);
const showWorkHistoryModal = ref(false);
const isEdit = ref(false);
const selectedTechnician = ref(null);

// 表单引用
const formRef = ref();

// 统计数据
const statistics = reactive({
  totalTechnicians: 12,
  totalChange: 2,
  onlineTechnicians: 8,
  onlineChange: 1,
  workingTechnicians: 5,
  workingChange: 0,
  averageRating: 4.6,
  ratingChange: 0.1,
});

// 搜索表单
const searchForm = reactive({
  name: '',
  specialty: '',
  status: '',
  experience: '',
});

// 人员表单
const form = reactive({
  name: '',
  employeeId: '',
  phone: '',
  idCard: '',
  specialty: [],
  experience: '',
  joinDate: null,
  status: 'online',
  bio: '',
  remark: '',
});

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入姓名' }],
  employeeId: [{ required: true, message: '请输入工号' }],
  phone: [{ required: true, message: '请输入联系电话' }],
  idCard: [{ required: true, message: '请输入身份证号' }],
  specialty: [{ required: true, message: '请选择专业领域' }],
  experience: [{ required: true, message: '请输入工作经验' }],
  joinDate: [{ required: true, message: '请选择入职时间' }],
  status: [{ required: true, message: '请选择状态' }],
};

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

// 人员数据
const technicians = ref([
  {
    id: 1,
    name: '张师傅',
    employeeId: 'T001',
    phone: '13800138001',
    idCard: '110101199001011234',
    specialty: ['electrical', 'appliance'],
    experience: 8,
    joinDate: '2020-03-15',
    status: 'working',
    rating: 4.8,
    ratingCount: 156,
    workload: 75,
    bio: '专业电气维修8年经验，擅长空调、冰箱等家电维修',
    remark: '技术过硬，服务态度好',
  },
  {
    id: 2,
    name: '李师傅',
    employeeId: 'T002',
    phone: '13800138002',
    idCard: '110101199002022345',
    specialty: ['plumbing', 'structure'],
    experience: 6,
    joinDate: '2021-06-20',
    status: 'online',
    rating: 4.6,
    ratingCount: 98,
    workload: 45,
    bio: '水管维修专家，有丰富的结构维修经验',
    remark: '工作认真负责',
  },
  {
    id: 3,
    name: '王师傅',
    employeeId: 'T003',
    phone: '13800138003',
    idCard: '110101199003033456',
    specialty: ['furniture', 'appliance'],
    experience: 4,
    joinDate: '2022-01-10',
    status: 'online',
    rating: 4.5,
    ratingCount: 67,
    workload: 30,
    bio: '家具维修能手，也擅长小家电维修',
    remark: '年轻有为，学习能力强',
  },
  {
    id: 4,
    name: '赵师傅',
    employeeId: 'T004',
    phone: '13800138004',
    idCard: '110101199004044567',
    specialty: ['electrical', 'plumbing'],
    experience: 10,
    joinDate: '2019-08-12',
    status: 'leave',
    rating: 4.9,
    ratingCount: 203,
    workload: 0,
    bio: '资深维修师傅，电气和水管维修都很精通',
    remark: '技术全面，经验丰富',
  },
]);

// 工作记录数据
const workHistoryData = ref([
  {
    id: 1,
    workOrderNumber: 'WO-2024-001',
    roomNumber: '101',
    type: 'electrical',
    status: 'completed',
    startTime: '2024-01-15 09:30',
    endTime: '2024-01-15 11:30',
    rating: 5,
    comment: '维修及时，技术专业',
  },
  {
    id: 2,
    workOrderNumber: 'WO-2024-002',
    roomNumber: '205',
    type: 'appliance',
    status: 'completed',
    startTime: '2024-01-14 14:00',
    endTime: '2024-01-14 15:30',
    rating: 4,
    comment: '服务态度好',
  },
]);

// 表格列定义
const columns = [
  {
    title: '姓名',
    dataIndex: 'name',
    key: 'name',
    width: 120,
  },
  {
    title: '专业领域',
    dataIndex: 'specialty',
    key: 'specialty',
    width: 150,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '工作经验',
    dataIndex: 'experience',
    key: 'experience',
    width: 100,
    customRender: ({ text }: any) => `${text}年`,
  },
  {
    title: '评分',
    dataIndex: 'rating',
    key: 'rating',
    width: 120,
  },
  {
    title: '工作量',
    dataIndex: 'workload',
    key: 'workload',
    width: 120,
  },
  {
    title: '联系电话',
    dataIndex: 'phone',
    key: 'phone',
    width: 120,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right',
  },
];

// 工作记录表格列定义
const workHistoryColumns = [
  {
    title: '工单号',
    dataIndex: 'workOrderNumber',
    key: 'workOrderNumber',
    width: 120,
  },
  {
    title: '房间号',
    dataIndex: 'roomNumber',
    key: 'roomNumber',
    width: 80,
  },
  {
    title: '维修类型',
    dataIndex: 'type',
    key: 'type',
    width: 100,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '开始时间',
    dataIndex: 'startTime',
    key: 'startTime',
    width: 150,
  },
  {
    title: '结束时间',
    dataIndex: 'endTime',
    key: 'endTime',
    width: 150,
  },
  {
    title: '评分',
    dataIndex: 'rating',
    key: 'rating',
    width: 80,
  },
];

// 过滤后的人员数据
const filteredTechnicians = computed(() => {
  let result = technicians.value;

  if (searchForm.name) {
    result = result.filter((item) =>
      item.name.toLowerCase().includes(searchForm.name.toLowerCase()),
    );
  }

  if (searchForm.specialty) {
    result = result.filter((item) =>
      item.specialty.includes(searchForm.specialty),
    );
  }

  if (searchForm.status) {
    result = result.filter((item) => item.status === searchForm.status);
  }

  if (searchForm.experience) {
    const [min, max] = searchForm.experience.split('-').map(Number);
    result = result.filter((item) => {
      return max
        ? item.experience >= min && item.experience <= max
        : item.experience >= min;
    });
  }

  return result;
});

// 状态和类型相关函数
const getStatusColor = (status: string) => {
  const colors = {
    online: 'green',
    offline: 'default',
    working: 'blue',
    leave: 'orange',
  };
  return colors[status] || 'default';
};

const getStatusText = (status: string) => {
  const texts = {
    online: '在线',
    offline: '离线',
    working: '工作中',
    leave: '请假',
  };
  return texts[status] || status;
};

const getSpecialtyColor = (specialty: string) => {
  const colors = {
    electrical: 'blue',
    plumbing: 'cyan',
    appliance: 'purple',
    furniture: 'orange',
    structure: 'red',
  };
  return colors[specialty] || 'default';
};

const getSpecialtyText = (specialty: string) => {
  const texts = {
    electrical: '电气',
    plumbing: '水管',
    appliance: '家电',
    furniture: '家具',
    structure: '结构',
  };
  return texts[specialty] || specialty;
};

const getWorkloadStatus = (workload: number) => {
  if (workload >= 80) return 'exception';
  if (workload >= 60) return 'normal';
  return 'success';
};

const getWorkOrderStatusColor = (status: string) => {
  const colors = {
    pending: 'orange',
    processing: 'blue',
    completed: 'green',
    cancelled: 'red',
  };
  return colors[status] || 'default';
};

const getWorkOrderStatusText = (status: string) => {
  const texts = {
    pending: '待处理',
    processing: '处理中',
    completed: '已完成',
    cancelled: '已取消',
  };
  return texts[status] || status;
};

// 事件处理函数
const handleSearch = () => {
  pagination.current = 1;
  message.success('搜索完成');
};

const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    specialty: '',
    status: '',
    experience: '',
  });
  pagination.current = 1;
  message.success('重置完成');
};

const handleSave = async () => {
  try {
    await formRef.value.validate();
    if (isEdit.value) {
      message.success('人员信息更新成功');
    } else {
      message.success('人员添加成功');
    }
    showAddModal.value = false;
    resetForm();
  } catch (error) {
    console.error('表单验证失败:', error);
  }
};

const handleCancel = () => {
  showAddModal.value = false;
  resetForm();
};

const viewDetail = (record: any) => {
  selectedTechnician.value = record;
  showDetailModal.value = true;
};

const editTechnician = (record: any) => {
  isEdit.value = true;
  Object.assign(form, record);
  showAddModal.value = true;
};

const viewWorkHistory = (record: any) => {
  selectedTechnician.value = record;
  showWorkHistoryModal.value = true;
};

const resetForm = () => {
  Object.assign(form, {
    name: '',
    employeeId: '',
    phone: '',
    idCard: '',
    specialty: [],
    experience: '',
    joinDate: null,
    status: 'online',
    bio: '',
    remark: '',
  });
  isEdit.value = false;
};

onMounted(() => {
  // 初始化数据
  pagination.total = technicians.value.length;
});
</script>

<template>
  <div class="technicians-management">
    <div class="page-header">
      <h2>维修人员管理</h2>
      <Button type="primary" @click="showAddModal = true">
        <IconifyIcon icon="ant-design:user-add-outlined" />
        添加人员
      </Button>
    </div>

    <!-- 统计卡片 -->
    <Row :gutter="16" class="statistics-row">
      <Col :span="6">
        <StatisticsCard
          title="总人数"
          :value="statistics.totalTechnicians"
          :change="statistics.totalChange"
          icon="ant-design:team-outlined"
          color="#1890ff"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="在线"
          :value="statistics.onlineTechnicians"
          :change="statistics.onlineChange"
          icon="ant-design:check-circle-outlined"
          color="#52c41a"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="工作中"
          :value="statistics.workingTechnicians"
          :change="statistics.workingChange"
          icon="ant-design:tool-outlined"
          color="#faad14"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="平均评分"
          :value="statistics.averageRating"
          :change="statistics.ratingChange"
          icon="ant-design:star-outlined"
          color="#722ed1"
        />
      </Col>
    </Row>

    <!-- 搜索表单 -->
    <Card class="search-card">
      <Form layout="inline" :model="searchForm" class="search-form">
        <FormItem label="姓名">
          <Input
            v-model:value="searchForm.name"
            placeholder="请输入姓名"
            allow-clear
          />
        </FormItem>
        <FormItem label="专业领域">
          <Select
            v-model:value="searchForm.specialty"
            placeholder="请选择专业领域"
            allow-clear
            style="width: 120px"
          >
            <SelectOption value="electrical">电气</SelectOption>
            <SelectOption value="plumbing">水管</SelectOption>
            <SelectOption value="appliance">家电</SelectOption>
            <SelectOption value="furniture">家具</SelectOption>
            <SelectOption value="structure">结构</SelectOption>
          </Select>
        </FormItem>
        <FormItem label="状态">
          <Select
            v-model:value="searchForm.status"
            placeholder="请选择状态"
            allow-clear
            style="width: 120px"
          >
            <SelectOption value="online">在线</SelectOption>
            <SelectOption value="offline">离线</SelectOption>
            <SelectOption value="working">工作中</SelectOption>
            <SelectOption value="leave">请假</SelectOption>
          </Select>
        </FormItem>
        <FormItem label="工作经验">
          <Select
            v-model:value="searchForm.experience"
            placeholder="请选择经验"
            allow-clear
            style="width: 120px"
          >
            <SelectOption value="0-2">0-2年</SelectOption>
            <SelectOption value="3-5">3-5年</SelectOption>
            <SelectOption value="6-10">6-10年</SelectOption>
            <SelectOption value="10+">10年以上</SelectOption>
          </Select>
        </FormItem>
        <FormItem>
          <Space>
            <Button type="primary" @click="handleSearch">
              <IconifyIcon icon="ant-design:search-outlined" />
              搜索
            </Button>
            <Button @click="handleReset">
              <IconifyIcon icon="ant-design:reload-outlined" />
              重置
            </Button>
          </Space>
        </FormItem>
      </Form>
    </Card>

    <!-- 人员表格 -->
    <Card class="table-card">
      <Table
        :columns="columns"
        :data-source="filteredTechnicians"
        :pagination="pagination"
        :loading="loading"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'name'">
            <div class="technician-info">
              <div class="technician-name">{{ record.name }}</div>
              <div class="technician-id">ID: {{ record.employeeId }}</div>
            </div>
          </template>
          <template v-else-if="column.key === 'specialty'">
            <Space wrap>
              <Tag
                v-for="item in record.specialty"
                :key="item"
                :color="getSpecialtyColor(item)"
              >
                {{ getSpecialtyText(item) }}
              </Tag>
            </Space>
          </template>
          <template v-else-if="column.key === 'status'">
            <Tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'rating'">
            <div class="rating-info">
              <span class="rating-score">{{ record.rating }}</span>
              <span class="rating-count">({{ record.ratingCount }}条评价)</span>
            </div>
          </template>
          <template v-else-if="column.key === 'workload'">
            <Progress
              :percent="record.workload"
              :status="getWorkloadStatus(record.workload)"
              size="small"
            />
          </template>
          <template v-else-if="column.key === 'action'">
            <Space>
              <Button type="link" size="small" @click="viewDetail(record)">
                查看
              </Button>
              <Button type="link" size="small" @click="editTechnician(record)">
                编辑
              </Button>
              <Button type="link" size="small" @click="viewWorkHistory(record)">
                工作记录
              </Button>
            </Space>
          </template>
        </template>
      </Table>
    </Card>

    <!-- 新建/编辑人员弹窗 -->
    <Modal
      v-model:open="showAddModal"
      :title="isEdit ? '编辑维修人员' : '添加维修人员'"
      width="600px"
      @ok="handleSave"
      @cancel="handleCancel"
    >
      <Form ref="formRef" :model="form" :rules="rules" layout="vertical">
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="姓名" name="name">
              <Input v-model:value="form.name" placeholder="请输入姓名" />
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="工号" name="employeeId">
              <Input v-model:value="form.employeeId" placeholder="请输入工号" />
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="联系电话" name="phone">
              <Input v-model:value="form.phone" placeholder="请输入联系电话" />
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="身份证号" name="idCard">
              <Input v-model:value="form.idCard" placeholder="请输入身份证号" />
            </FormItem>
          </Col>
        </Row>
        <FormItem label="专业领域" name="specialty">
          <Select
            v-model:value="form.specialty"
            placeholder="选择专业领域"
            mode="multiple"
          >
            <SelectOption value="electrical">电气维修</SelectOption>
            <SelectOption value="plumbing">水管维修</SelectOption>
            <SelectOption value="appliance">家电维修</SelectOption>
            <SelectOption value="furniture">家具维修</SelectOption>
            <SelectOption value="structure">结构维修</SelectOption>
          </Select>
        </FormItem>
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="工作经验" name="experience">
              <Input
                v-model:value="form.experience"
                placeholder="工作经验（年）"
              />
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="入职时间" name="joinDate">
              <DatePicker
                v-model:value="form.joinDate"
                placeholder="选择入职时间"
                style="width: 100%"
              />
            </FormItem>
          </Col>
        </Row>
        <FormItem label="状态" name="status">
          <Select v-model:value="form.status" placeholder="选择状态">
            <SelectOption value="online">在线</SelectOption>
            <SelectOption value="offline">离线</SelectOption>
            <SelectOption value="working">工作中</SelectOption>
            <SelectOption value="leave">请假</SelectOption>
          </Select>
        </FormItem>
        <FormItem label="个人简介" name="bio">
          <Textarea v-model:value="form.bio" placeholder="个人简介" :rows="3" />
        </FormItem>
        <FormItem label="备注" name="remark">
          <Textarea
            v-model:value="form.remark"
            placeholder="备注信息"
            :rows="2"
          />
        </FormItem>
      </Form>
    </Modal>

    <!-- 人员详情弹窗 -->
    <Modal
      v-model:open="showDetailModal"
      title="人员详情"
      width="700px"
      :footer="null"
    >
      <Descriptions :column="2" bordered>
        <DescriptionsItem label="姓名">
          {{ selectedTechnician?.name }}
        </DescriptionsItem>
        <DescriptionsItem label="工号">
          {{ selectedTechnician?.employeeId }}
        </DescriptionsItem>
        <DescriptionsItem label="联系电话">
          {{ selectedTechnician?.phone }}
        </DescriptionsItem>
        <DescriptionsItem label="身份证号">
          {{ selectedTechnician?.idCard }}
        </DescriptionsItem>
        <DescriptionsItem label="专业领域">
          <Space wrap>
            <Tag
              v-for="item in selectedTechnician?.specialty"
              :key="item"
              :color="getSpecialtyColor(item)"
            >
              {{ getSpecialtyText(item) }}
            </Tag>
          </Space>
        </DescriptionsItem>
        <DescriptionsItem label="状态">
          <Tag :color="getStatusColor(selectedTechnician?.status)">
            {{ getStatusText(selectedTechnician?.status) }}
          </Tag>
        </DescriptionsItem>
        <DescriptionsItem label="工作经验">
          {{ selectedTechnician?.experience }}年
        </DescriptionsItem>
        <DescriptionsItem label="入职时间">
          {{ selectedTechnician?.joinDate }}
        </DescriptionsItem>
        <DescriptionsItem label="评分">
          {{ selectedTechnician?.rating }} ({{
            selectedTechnician?.ratingCount
          }}条评价)
        </DescriptionsItem>
        <DescriptionsItem label="工作量">
          <Progress
            :percent="selectedTechnician?.workload"
            :status="getWorkloadStatus(selectedTechnician?.workload)"
            size="small"
          />
        </DescriptionsItem>
        <DescriptionsItem label="个人简介" :span="2">
          {{ selectedTechnician?.bio || '无' }}
        </DescriptionsItem>
        <DescriptionsItem label="备注" :span="2">
          {{ selectedTechnician?.remark || '无' }}
        </DescriptionsItem>
      </Descriptions>
    </Modal>

    <!-- 工作记录弹窗 -->
    <Modal
      v-model:open="showWorkHistoryModal"
      title="工作记录"
      width="800px"
      :footer="null"
    >
      <Table
        :columns="workHistoryColumns"
        :data-source="workHistoryData"
        :pagination="{ pageSize: 5 }"
        size="small"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <Tag :color="getWorkOrderStatusColor(record.status)">
              {{ getWorkOrderStatusText(record.status) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'rating'">
            <span class="rating-display">{{ record.rating }}分</span>
          </template>
        </template>
      </Table>
    </Modal>
  </div>
</template>

<style scoped>
.technicians-management {
  padding: 24px;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.statistics-row {
  margin-bottom: 24px;
}

.search-card {
  margin-bottom: 16px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.table-card {
  margin-bottom: 16px;
}

.technician-info {
  display: flex;
  flex-direction: column;
}

.technician-name {
  margin-bottom: 4px;
  font-weight: 500;
}

.technician-id {
  font-size: 12px;
  color: #666;
}

.rating-info {
  display: flex;
  gap: 4px;
  align-items: center;
}

.rating-score {
  font-weight: 500;
  color: #faad14;
}

.rating-count {
  font-size: 12px;
  color: #666;
}

.rating-display {
  font-weight: 500;
  color: #faad14;
}

:deep(.ant-card-body) {
  padding: 12px;
}

:deep(.ant-table-thead > tr > th) {
  font-weight: 500;
  background-color: #fafafa;
}

:deep(.ant-descriptions-item-label) {
  width: 120px;
  font-weight: 500;
}
</style>
